//编辑，详情动态表格
<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{updataFull, updataDialogWidth}"
      :fullscreen="isfullscreen"
      :width="setDialogWidth('1200px')"
      :visible="visible"
      :title="$t('FAULT_LOCATION_RESULT')"
      @open="open"
      @close="close"
    >
      <div class="flex flex-wrap">
        <div class="w-50 mb-10">
          {{ $t('FAULTY_SERVICE_NAME') }}：
          {{ bizOpenData.bizName }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('FAULT_SERVICE_CODE') }}：
          {{ bizOpenData.resourceCode }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('A_END_STATION') }}：
          {{ getRegionName(bizOpenData.startStationId) }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('Z_END_STATION') }}：
          {{ getRegionName(bizOpenData.endStationId) }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('ANODE') }}：
          {{ bizOpenData.startNode ? bizOpenData.startNode.nodeName : '' }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('ZNODE') }}：
          {{ bizOpenData.endNode ? bizOpenData.endNode.nodeName : '' }}
        </div>
      </div>
      <div v-if="tableHead.length" class="fault-location-table flex mb-10">
        <!-- 序号 -->
        <div>
          <div class="table-header">
            <div class="table-cell order">{{ $t('SEQUENCE') }}</div>
          </div>
          <div class="table-row">
            <div class="table-cell order">1</div>
            <div v-if="segmentList.length === 2" class="table-cell order">2</div>
            <div class="table-cell w-auto holder" />
          </div>
        </div>
        <div class="flex-1 content">
          <!-- 表头 -->
          <div class="table-header flex align-center">
            <div v-for="segment in tableHead" :key="segment.segmentId" class="segment-item">
              <div class="table-cell w-auto" :style="{maxWidth: (segment.cableId ? 450 : 300) + 'px'}">{{ segment.segmentName }}</div>
              <div class="flex">
                <div class="table-cell">
                  {{ segment.startNode ? segment.startNode.nodeName : '--' }}
                </div>
                <div v-if="segment.cableId && segment.cable" class="table-cell">
                  {{ segment.cable.cableName }}
                </div>
                <div class="table-cell">
                  {{ segment.endNode ? segment.endNode.nodeName : '--' }}
                </div>
              </div>
            </div>
          </div>
          <!-- 表格内容 -->
          <div
            v-for="(row, rowIndex) in segmentList"
            :key="rowIndex"
            class="table-row flex align-center"
          >
            <!-- 逻辑网段 -->
            <div
              v-for="(logicChannel, logicIndex) in row.logicChannel.segmentList"
              :key="logicChannel.segmentId"
              class="flex-column"
              :class="getStatus(logicChannel) && !getBtnStatus(logicChannel) ? 'error-box' : ''"
            >
              <!-- 网段 -->
              <div class="flex">
                <div
                  v-for="segment in logicChannel.physicStruct"
                  :key="segment.segmentId"
                  class="flex"
                >
                  <div class="table-cell">
                    <el-button
                      v-if="
                        segment.startPortCategory === 'VARIABLE_POINT' &&
                          testResult[segment.startPortId] &&
                          testResult[segment.startPortId].dataNum
                      "
                      type="text"
                      class="el-icon-document"
                      @click="portClick(segment.startPortId, segment.startPort.portName)"
                    />
                    {{
                      segment.startPort
                        ? $utils.handleServiceI18n(segment.startPort.portName)
                        : '--'
                    }}
                  </div>
                  <div v-if="segment.fiberId" class="table-cell">
                    {{ segment.fiber.fiberName }}
                  </div>
                  <div class="table-cell">
                    <el-button
                      v-if="
                        segment.endPortCategory === 'VARIABLE_POINT' &&
                          testResult[segment.endPortId] &&
                          testResult[segment.endPortId].dataNum
                      "
                      type="text"
                      class="el-icon-document"
                      @click="portClick(segment.endPortId, segment.endPort.portName)"
                    />
                    {{
                      segment.endPort ? $utils.handleServiceI18n(segment.endPort.portName) : '--'
                    }}
                  </div>
                </div>
              </div>
              <div class="table-cell w-auto">
                <el-button
                  v-if="logicIndex !== 0 && logicIndex !== row.logicChannel.segmentList.length - 1"
                  class="el-icon-thumb"
                  type="text"
                  :disabled="getBtnStatus(logicChannel)"
                  @click="$debounce(setNoFault, logicChannel)"
                >{{ $t('SET_NO_FAULT') }}</el-button>
              </div>
            </div>
          </div>
        </div>
        <!-- 操作 -->
        <div>
          <div class="table-header border-left">
            <div class="table-cell order w-auto">{{ $t('OPERATE') }}</div>
          </div>
          <div class="table-row border-left">
            <div class="table-cell order w-auto">
              <el-button
                class="el-icon-thumb"
                type="text"
                :disabled="getOperateBtnStatus(segmentList[0])"
                @click="$debounce(setNoFault, { index: 0, isAll: true })"
              >{{ $t('ALL_SET_NO_FAULT') }}</el-button>
            </div>
            <div v-if="segmentList.length === 2" class="table-cell order w-auto">
              <el-button
                class="el-icon-thumb"
                type="text"
                :disabled="getOperateBtnStatus(segmentList[1])"
                @click="$debounce(setNoFault, { index: 1, isAll: true })"
              >{{ $t('ALL_SET_NO_FAULT') }}</el-button>
            </div>
            <div class="table-cell w-auto holder" />
          </div>
        </div>
      </div>
      <template v-slot:footer>
        <el-button @click="close">{{ $t('CLOSE') }}</el-button>
      </template>
    </el-dialog>
    <result-chart :visible="showParams" :cur-result="curResult" @close="showParams = false" @closeAll="closeAll" />
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import faultLocationApi from '@/api/oen/FaultLocationApi'
  import ResultChart from './ResultChart'

  export default {
    name: 'FaultLocation',
    components: { ResultChart },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        segmentList: [],
        curResult: {},
        bizOpenData: {},
        showParams: false,
        testResult: {},
        tableHead: [],
        impactChannelIds: []
      }
    },
    computed: {
      ...mapGetters(['baseRegionList']),
      permission() {
        return this.$store.getters.getAuthData('biz:faultLocation')
      }
    },
    methods: {
      open() {
        this.segmentList = []
        this.tableHead = []
        this.getOtdrParam()
        faultLocationApi
          .detail({
            id: this.rowData.id
          })
          .then(res => {
            this.bizOpenData = { ...res.bizOpen }
            this.segmentList = res.channelMergeList
            this.tableHead = res.networkSegmentList || this.correctOrder(res.networkSegmentList)
            this.impactChannelIds = res.impactChannelIds || []
            this.checkOneSide()
          })
      },
      // 监测是否需要弹窗提示单面监测
      checkOneSide() {
        if (this.segmentList.length === 0 || !this.testResult.ready) return
        const isBothway = this.segmentList.every(i => {
          const segmentList = i.logicChannel.segmentList
          return segmentList.every((j, jIndex) => {
            if (jIndex === 0 || jIndex === segmentList.length - 1) {
              return true
            } else {
              return this.testResult[j.startPortId] && this.testResult[j.endPortId]
            }
          })
        })
        if (
          this.rowData.status === 'TEST' &&
          (!Object.keys(this.testResult).some(i => this.testResult[i].resultFault) ||
            !isBothway)
        ) {
          this.$message.warning(this.$t('TEST_ANOTHER_DIRECTION'))
        }
      },
      // 表头反向纠正
      correctOrder(data) {
        if (!data) return []
        return data.reduce((prev, curr, index) => {
          let start = 'start'
          let end = 'end'
          if (index !== 0 && prev[index - 1].endNodeId !== curr.startNodeId) {
            start = 'end'
            end = 'start'
          }
          const item = {
            ...curr,
            startNode: curr[start + 'Node'],
            startNodeCategory: curr[start + 'NodeCategory'],
            startNodeId: curr[start + 'NodeId'],
            startStationId: curr[start + 'StationId'],
            endNode: curr[end + 'Node'],
            endNodeCategory: curr[end + 'NodeCategory'],
            endNodeId: curr[end + 'NodeId'],
            endStationId: curr[end + 'StationId']
          }
          prev.push(item)
          return prev
        }, [])
      },
      // 测试结果状态
      getStatus(logicChannel) {
        return (
          (this.testResult[logicChannel.startPortId] &&
            this.testResult[logicChannel.startPortId].resultFault) ||
          (this.testResult[logicChannel.endPortId] &&
            this.testResult[logicChannel.endPortId].resultFault)
        )
      },
      // 置为无故障按钮状态
      getBtnStatus(logicChannel) {
        return logicChannel.physicStruct.every(i => this.impactChannelIds.includes(i.channelId))
      },
      // 操作 -- 置为无故障按钮状态
      getOperateBtnStatus(data) {
        return data.segmentChannelList.every(i => this.impactChannelIds.includes(i.channelId))
      },
      // 获取测试结果
      getOtdrParam() {
        this.testResult = {}
        faultLocationApi.testResult({ id: this.rowData.id }).then(res => {
          res = res || {}
          Object.keys(res).forEach(i => {
            if (res[i].dataNum) {
              res[i].resultFault =
                !res[i].targetFiberLength ||
                Math.abs(res[i].targetFiberLength - res[i].fiberLength) / res[i].targetFiberLength >
                0.02
            } else {
              res[i].resultFault = false
            }
          })
          this.testResult = res
          this.testResult.ready = true
          this.checkOneSide()
          console.log('res', res)
        })
      },
      // 测试参数点击
      portClick(portId, portName) {
        this.curResult = this.testResult[portId]
        this.curResult.orderIndex = portName
        this.showParams = true
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(i => i.regionId === stationId)
        return stationData ? stationData.regionName : ''
      },
      setNoFault(data) {
        this.$confirm(this.$t(data.isAll ? 'CONFIRM_ALL_NO_FAULT' : 'CONFIRM_NO_FAULT'), {
          type: 'warning'
        })
          .then(() => {
            // console.log('logicChannel', data)
            let channelIds = []
            if (data.isAll) {
              channelIds = this.segmentList[data.index].segmentChannelList.map(i => i.channelId)
            } else {
              channelIds = data.physicStruct.map(i => i.channelId)
            }
            // console.log('channelIds', channelIds)
            faultLocationApi
              .restoreStatus({
                id: this.rowData.id,
                channelIdList: channelIds,
                bizName: this.bizOpenData.bizName // 操作日志需要传递此参数
              })
              .then(res => {
                if (res) {
                  this.$message.success(this.$t('OPERATE_SUCCESS'))
                  this.close(true)
                } else {
                  this.$message.error(this.$t('OPERATEFAILED'))
                }
              })
          })
          .catch(() => {})
      },
      close(reload) {
        this.$emit('close', reload)
      },
      closeAll() {
        this.close(false)
        this.showParams = false
      }
    }
  }
</script>
<style scoped lang="scss">
  @import 'src/assets/css/mixin.module';

  .fault-location-table {
    width: 100%;
    background: transparent;
    border-top: 1px solid #fff;
    border-left: 1px solid #fff;
    @include font_color('tableTextThColor');
    @include themeify {
      border-top: 1px solid themed('tableBorderColor');
      border-left: 1px solid themed('tableBorderColor');
    }
    .content {
      overflow-x: auto;
      @include themeify {
        border-bottom: 1px solid themed('tableBorderColor');
        background-color: themed('tableBgTrColor');
      }
    }
    .table-header .table-cell {
      font-weight: 700;
      @include font_color('tableTextThColor');
      @include themeify {
        background-color: themed('tableBgThColor');
      }
    }

    .table-row {
      @include font_color('textColor');
      @include themeify {
        background-color: themed('tableBgTrColor');
      }
    }

    .table-cell {
      position: relative;
      width: 150px;
      height: 36px;
      padding: 6px 10px;
      text-align: center;
      line-height: 23px;
      border-bottom: 1px solid #fff;
      border-right: 1px solid #fff;
      overflow: hidden;
      // white-space: nowrap;
      white-space: pre;
      text-overflow: ellipsis;
      @include themeify {
        color: lighten(themed('textColor'), 10%);
        border-bottom: 1px solid themed('tableBorderColor');
        border-right: 1px solid themed('tableBorderColor');
      }
      &.order {
        flex: none;
        width: 50px;
        height: 72px;
        line-height: 58px;
      }
      &.w-auto {
        width: auto;
      }

      .el-button {
        margin-top: -3px;
      }

      .el-icon-document {
        position: absolute;
        left: 5px;
      }
    }
    .border-left {
      @include themeify {
        border-left: 1px solid themed('tableBorderColor');
      }
    }

    .error-box {
      box-shadow: inset 0px 0px 0px 2px red;
    }
    .holder {
      height: 7px;
      padding: 0;
    }
  }
</style>
